package com.wanwucs.timely;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.wanwucs.imagelibrary.ImageUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by chenhaitao on 2017/8/3.
 */

public class Image2TextActivity extends Activity {

    private Button btnParse,btnTimely;

    private ProgressDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image2text);
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在解析图片...");
        dialog.setCancelable(false);
        btnParse = (Button)findViewById(R.id.btn_parse);
        btnParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        decodeImage("rat-clipart-2-150x150.jpg");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.dismiss();
                                Toast.makeText(Image2TextActivity.this,"解析存储完毕",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }).start();
            }
        });

        btnTimely = (Button)findViewById(R.id.btn_timely);
        btnTimely.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Image2TextActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });


    }

    private void decodeImage(String imagePath){
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(imagePath);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            String content = ImageUtil.image2Text(bitmap);
            bitmap.recycle();
            saveToSDCard("rat-clipart-2-150x150.txt",content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public void saveToSDCard(String filename, String filecontent) throws Exception{
        File file = new File(Environment.getExternalStorageDirectory(),filename);
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(filecontent.getBytes());
        outStream.close();
    }
}
